package com.atguigu.paymentdemo.service.impl;

import com.atguigu.paymentdemo.entity.OrderInfo;
import com.atguigu.paymentdemo.entity.PaymentInfo;
import com.atguigu.paymentdemo.enums.OrderStatus;
import com.atguigu.paymentdemo.mapper.PaymentInfoMapper;
import com.atguigu.paymentdemo.service.OrderInfoService;
import com.atguigu.paymentdemo.service.PaymentInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {
    @Autowired
    private OrderInfoService orderInfoService;

    @Override
    public void insertInfo(Transaction transaction) {
        // 根据订单号插入数据
        OrderInfo one = orderInfoService.lambdaQuery().eq(OrderInfo::getOrderNo, transaction.getOutTradeNo()).one();
        if (one != null && one.getOrderStatus().equals(OrderStatus.SUCCESS)) {
            return;
        }

        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setOrderNo(transaction.getOutTradeNo());
        paymentInfo.setPaymentType(transaction.getBankType());
        paymentInfo.setTradeType(paymentInfo.getTradeType());
        paymentInfo.setTransactionId(transaction.getTransactionId());
        paymentInfo.setTradeState(transaction.getTradeState().toString());
        paymentInfo.setPayerTotal(transaction.getAmount().getPayerTotal());
        paymentInfo.setContent(transaction.toString());
        save(paymentInfo);
    }

    @Override
    public PaymentInfo findByOutOrderId(String outOrderId) {
        PaymentInfo one = lambdaQuery().eq(PaymentInfo::getOrderNo, outOrderId).one();
        return one;
    }

    @Override
    public void updatePayStatusByOrderNo(String outTradeNo, String type) {
        lambdaUpdate().eq(PaymentInfo::getOrderNo,outTradeNo)
                .set(PaymentInfo::getTradeState,type)
                .update();
    }
}
